import axios from "axios";
import Qs from "qs";
// import store from '@/store';

//post请求头设置
axios.defaults.baseURL = ""; // 测试
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
axios.defaults.withCredentials = true;

//请求拦截
axios.interceptors.request.use(
	config => {
		if (config.url !== '/login' || config.url !== '/') {
			config.headers.token = sessionStorage.getItem('token');
		}
		return config;
	},
	error => {
		return Promise.error(error);
	}
);

//响应拦截
axios.interceptors.response.use(response => {
	//返回状态码200，请求成功，否则抛出异常
	if (response.data.code === 200) {
		return Promise.resolve(response);
	} else {
		return Promise.reject(response);
	}
});

// Post请求
const post = (url, params) => {
	return axios({
		method: "post",
		url,
		data: Qs.stringify(params),
		timeout: 30000
	}).then(res => {
		console.log(res);
		return Promise.resolve(res);
	}).catch(err => {
		return Promise.reject(err);
	});
};

// Get请求
const get = (url, data) => {
	return axios({
		method: "get",
		url,
		params: data,
		timeout: 30000
	}).then(res => {
		return Promise.resolve(res);
	}).catch(err => {
		return Promise.reject(err);
	});
};

// 上传图片
const upPic = (url, params) => {
	let config = {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	};
	return axios({
		method: "post",
		url,
		data: params,
		config: config,
		timeout: 30000
	}).then(res => {
		return Promise.resolve(res);
	}).catch(err => {
		return Promise.reject(err);
	});
};

export {
	post,
	get,
	upPic
};